/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Assignment
 */
'use strict';

angular.module('flowableModeler').controller('FlowableAssignmentCtrl', ['$scope', '$modal', function ($scope, $modal) {

    // Config for the modal window
    var opts = {
        template: 'editor-app/configuration/properties/assignment-popup.html?version=' + Date.now(),
        scope: $scope
    };

    // Open the dialog
    _internalCreateModal(opts, $modal, $scope);
}]);

angular.module('flowableModeler').controller('FlowableAssignmentPopupCtrl',
    ['$rootScope', '$scope', '$translate', '$http', 'UserService', 'GroupService', function ($rootScope, $scope, $translate, $http, UserService, GroupService) {

        // Put json representing assignment on scope
        if ($scope.property.value !== undefined && $scope.property.value !== null
            && $scope.property.value.assignment !== undefined
            && $scope.property.value.assignment !== null) {

            $scope.assignment = $scope.property.value.assignment;
            if (typeof $scope.assignment.type === 'undefined') {
                $scope.assignment.type = 'static';
            }

        } else {
            $scope.assignment = {type: 'idm'};
        }

        $scope.popup = {
            assignmentObject: {
                type: $scope.assignment.type,
                idm: {
                    type: undefined,
                    assignee: undefined,
                    candidateUsers: [],
                    candidateGroups: []
                },
                static: {
                    assignee: undefined,
                    candidateUsers: [],
                    candidateGroups: []
                }
            }
        };

        $scope.assignmentOptions = [
            {id: "initiator", title: $translate.instant('PROPERTY.ASSIGNMENT.IDM.DROPDOWN.INITIATOR')},
            {id: "user", title: $translate.instant('PROPERTY.ASSIGNMENT.IDM.DROPDOWN.USER')},
            {id: "users", title: $translate.instant('PROPERTY.ASSIGNMENT.IDM.DROPDOWN.USERS')},
            {id: "groups", title: $translate.instant('PROPERTY.ASSIGNMENT.IDM.DROPDOWN.GROUPS')},
            {id: "custom", title: $translate.instant('自定义权限')}
        ];

        /* 自定义权限 */
        $scope.allocationOperations = [
            {id: 1, type: "user", title: "用户"},
            {id: 2, type: "dept", title: "部门"},
            {id: 3, type: "post", title: "岗位"},
            {id: 4, type: "group", title: "岗位组"},
            {id: 5, type: "level", title: "岗位等级"},
            {id: 6, type: "deptPost", title: "部门及岗位"}
        ];


        // TODO 其实这一部分应该可以删掉，历史数据数据需要...
        importingXML();

        // 导入xml，会出现自定义的数据无法回显
        function importingXML() {
            // 针对从外部导出的xml，会出现$scope.assignment.idm.showType为空，需要单独处理
            if (!!$scope.assignment.idm && !$scope.assignment.idm.showType && $scope.assignment.idm.candidateGroups.length > 0) {//为空
                var firstId = $scope.assignment.idm.candidateGroups[0].id;
                if (!!firstId) {
                    var boo = firstId.includes("_");
                    if (boo) {
                        var type = firstId.split("_")[0];
                        var operation = $scope.allocationOperations.find(it => (it.id - 1) == type);
                        $scope.allocation = operation.type;
                        $scope.assignment.idm.customType = operation.type;
                        $scope.assignment.idm.showType = "custom";
                        for (var i = 0; i < $scope.assignmentOptions.length; i++) {
                            if ($scope.assignmentOptions[i].id == $scope.assignment.idm.showType) {
                                $scope.assignmentOption = $scope.assignmentOptions[i];
                                break;
                            }
                        }
                    }
                }
            }
        }

        // TODO 针对旧数据做的一些处理，其实可以删除...
        if($scope.popup.assignmentObject.type==='idm'  && $scope.assignment.idm){
            if(!$scope.assignment.idm.customType && !$scope.assignment.idm.showType){
                console.log("历史数据异常数据（那些选择候选组的）需要处理一下.......");
                $scope.assignment.idm.customType="-1"
                $scope.assignment.idm.showType="groups"
            }
        }

        //打开弹窗，回显
        // if ($scope.assignment.idm && $scope.assignment.idm.type) {
        if ($scope.assignment.idm && $scope.assignment.idm.showType) {
            for (var i = 0; i < $scope.assignmentOptions.length; i++) {
                // if ($scope.assignmentOptions[i].id == $scope.assignment.idm.type) {
                if ($scope.assignmentOptions[i].id == $scope.assignment.idm.showType) {
                    $scope.assignmentOption = $scope.assignmentOptions[i];
                    break;
                }
            }
        }

        // fill the IDM area
        if (!$scope.assignmentOption) {
            // Default, first time opening the popup
            $scope.assignmentOption = $scope.assignmentOptions[0];
        } else {
            // Values already filled
            if ($scope.assignment.idm) { //fill the IDM tab
                if ($scope.assignment.idm.assignee) {
                    if ($scope.assignment.idm.assignee.id) {
                        $scope.popup.assignmentObject.idm.assignee = $scope.assignment.idm.assignee;
                    } else {
                        $scope.popup.assignmentObject.idm.assignee = {email: $scope.assignment.idm.assignee.email};
                    }
                }

                if ($scope.assignment.idm.candidateUsers && $scope.assignment.idm.candidateUsers.length > 0) {
                    for (var i = 0; i < $scope.assignment.idm.candidateUsers.length; i++) {
                        $scope.popup.assignmentObject.idm.candidateUsers.push($scope.assignment.idm.candidateUsers[i]);
                    }
                }

                if ($scope.assignment.idm.candidateGroups && $scope.assignment.idm.candidateGroups.length > 0) {
                    for (var i = 0; i < $scope.assignment.idm.candidateGroups.length; i++) {
                        $scope.popup.assignmentObject.idm.candidateGroups.push($scope.assignment.idm.candidateGroups[i]);
                    }
                }
            }
        }

        //fill the static area
        if ($scope.assignment.assignee) {
            $scope.popup.assignmentObject.static.assignee = $scope.assignment.assignee;
        }

        if ($scope.assignment.candidateUsers && $scope.assignment.candidateUsers.length > 0) {
            for (var i = 0; i < $scope.assignment.candidateUsers.length; i++) {
                $scope.popup.assignmentObject.static.candidateUsers.push($scope.assignment.candidateUsers[i]);
            }
        }

        if ($scope.assignment.candidateGroups && $scope.assignment.candidateGroups.length > 0) {
            for (var i = 0; i < $scope.assignment.candidateGroups.length; i++) {
                $scope.popup.assignmentObject.static.candidateGroups.push($scope.assignment.candidateGroups[i]);
            }
        }

        /**
         * 自定义类型切换方法
         * @param e 0：初始化，1：切换
         */
        $scope.allocationChange = function (e) {
            if (e === "1") {//切换时，清空所有数据
                $scope.popup = {
                    assignmentObject: {
                        // type: $scope.assignment.type,
                        type: $scope.popup.assignmentObject.type,
                        idm: {
                            type: undefined,
                            assignee: undefined,
                            candidateUsers: [],
                            candidateGroups: []
                        },
                        static: {
                            assignee: undefined,
                            candidateUsers: [{value: ''}],
                            candidateGroups: [{value: ''}]
                        }
                    }
                };

                // 用户数据
                $scope.userSelectData = [];
                // 部门数据
                $scope.deptSelectData = [];
                // 岗位数据
                $scope.postSelectData = [];
                // 岗位组数据
                $scope.groupSelectData = [];
                // 岗位等级数据
                $scope.levelSelectData = [];
                // 部门岗位数据
                $scope.deptPostSelectData = [{dept: "", post: ""}];
            }
            console.log("选中类型：", $scope.allocation);
            console.log("需要回显的信息：", $scope.popup.assignmentObject.idm);
            if ($scope.allocationSelect) {
                $scope.allocation = $scope.allocationSelect.type;
            } else {
                $scope.allocation = "-1";
            }
            if ($scope.allocation === 'user') {
                console.log("设置用户");
                $scope.tableLoading = false;
                var url = localStorage.getItem("baseURL") + "/new-flowable/workflow/findAllUser";
                $http({
                    method: 'GET',
                    url: url,
                    headers: {
                        accessToken: localStorage.getItem("accessToken")
                    }
                }).then(function (response) {
                    var data = response.data;
                    if (data.success) {
                        // 回显选中
                        if ('user' === $scope.allocation && $scope.popup.assignmentObject.idm.candidateUsers.length > 0) {
                            $scope.userSelectData = $scope.popup.assignmentObject.idm.candidateUsers;
                            $scope.userTableData = data.result.map(user => {
                                var find = $scope.popup.assignmentObject.idm.candidateUsers.find(it => it.id === user.id)
                                user.isChecked = !!find;
                                return user;
                            });
                        } else {// 默认没有值
                            $scope.userTableData = data.result.map(user => {
                                user.isChecked = false;
                                return user;
                            });
                        }
                        $scope.tableLoading = true;
                    }
                }, function (error) {
                    console.log("请求失败的回调函数 ", error);
                });
            } else if ($scope.allocation === 'dept') {
                console.log("设置部门");
                $scope.tableLoading = false;
                var url = localStorage.getItem("baseURL") + "/new-flowable/workflow/findAllDepart";
                $http({
                    method: 'GET',
                    url: url,
                    headers: {
                        accessToken: localStorage.getItem("accessToken")
                    }
                }).then(function (response) {
                    var data = response.data;
                    if (data.success) {
                        // 回显选中
                        if ('dept' === $scope.allocation && $scope.popup.assignmentObject.idm.candidateGroups.length > 0) {
                            $scope.deptSelectData = $scope.popup.assignmentObject.idm.candidateGroups;
                            $scope.deptTableData = data.result.map(dept => {
                                var find = $scope.popup.assignmentObject.idm.candidateGroups.find(it => it.id === dept.id)
                                dept.isChecked = !!find;
                                return dept;
                            });
                        } else {// 默认没有值
                            $scope.deptTableData = data.result.map(dept => {
                                dept.isChecked = false;
                                return dept;
                            });
                        }
                        $scope.tableLoading = true;
                    }
                }, function (error) {
                    console.log("请求失败的回调函数 ", error);
                });
            } else if ($scope.allocation === 'post') {
                console.log("设置岗位");
                $scope.tableLoading = false;
                var url = localStorage.getItem("baseURL") + "/new-flowable/workflow/findAllPosition";
                $http({
                    method: 'GET',
                    url: url,
                    headers: {
                        accessToken: localStorage.getItem("accessToken")
                    }
                }).then(function (response) {
                    var data = response.data;
                    if (data.success) {
                        // 回显选中
                        if ('post' === $scope.allocation && $scope.popup.assignmentObject.idm.candidateGroups.length > 0) {
                            $scope.postSelectData = $scope.popup.assignmentObject.idm.candidateGroups;
                            $scope.postTableData = data.result.map(post => {
                                var find = $scope.popup.assignmentObject.idm.candidateGroups.find(it => it.id === post.id)
                                post.isChecked = !!find;
                                return post;
                            });
                        } else {// 默认没有值
                            $scope.postTableData = data.result.map(post => {
                                post.isChecked = false;
                                return post;
                            });
                        }
                        $scope.tableLoading = true;
                    }
                }, function (error) {
                    console.log("请求失败的回调函数 ", error);
                });
            } else if ($scope.allocation === 'group') {
                console.log("设置岗位组");
                $scope.tableLoading = false;
                var url = localStorage.getItem("baseURL") + "/new-flowable/workflow/findAllPositionGroup";
                $http({
                    method: 'GET',
                    url: url,
                    headers: {
                        accessToken: localStorage.getItem("accessToken")
                    }
                }).then(function (response) {
                    var data = response.data;
                    if (data.success) {
                        // 回显选中
                        if ('group' === $scope.allocation && $scope.popup.assignmentObject.idm.candidateGroups.length > 0) {
                            $scope.groupSelectData = $scope.popup.assignmentObject.idm.candidateGroups;
                            $scope.groupTableData = data.result.map(group => {
                                var find = $scope.popup.assignmentObject.idm.candidateGroups.find(it => it.id === group.id)
                                group.isChecked = !!find;
                                return group;
                            });
                        } else {// 默认没有值
                            $scope.groupTableData = data.result.map(group => {
                                group.isChecked = false;
                                return group;
                            });
                        }
                        $scope.tableLoading = true;
                    }
                }, function (error) {
                    console.log("请求失败的回调函数 ", error);
                });
            } else if ($scope.allocation === 'level') {
                console.log("设置等级");
                $scope.tableLoading = false;
                var url = localStorage.getItem("baseURL") + "/new-flowable/workflow/findAllPositionLevel";
                $http({
                    method: 'GET',
                    url: url,
                    headers: {
                        accessToken: localStorage.getItem("accessToken")
                    }
                }).then(function (response) {
                    var data = response.data;
                    if (data.success) {
                        // 回显选中
                        if ('level' === $scope.allocation && $scope.popup.assignmentObject.idm.candidateGroups.length > 0) {
                            $scope.levelSelectData = $scope.popup.assignmentObject.idm.candidateGroups;
                            $scope.levelTableData = data.result.map(level => {
                                var find = $scope.popup.assignmentObject.idm.candidateGroups.find(it => it.id === level.id)
                                level.isChecked = !!find;
                                return level;
                            });
                        } else {// 默认没有值
                            $scope.levelTableData = data.result.map(level => {
                                level.isChecked = false;
                                return level;
                            });
                        }
                        $scope.tableLoading = true;
                    }
                }, function (error) {
                    console.log("请求失败的回调函数 ", error);
                });
            } else if ($scope.allocation === 'deptPost') {
                console.log("设置部门岗位");
                /*----------------------------------------部门-------------------------------------------*/
                var url = localStorage.getItem("baseURL") + "/new-flowable/workflow/findAllDepart";
                $http({
                    method: 'GET',
                    url: url,
                    headers: {
                        accessToken: localStorage.getItem("accessToken")
                    }
                }).then(function (response) {
                    var data = response.data;
                    if (data.success) {
                        // 回显选中
                        if ('deptPost' === $scope.allocation && $scope.popup.assignmentObject.idm.candidateGroups.length > 0) {
                            $scope.dpDeptTableData = data.result;
                            var candidateGroups = $scope.popup.assignmentObject.idm.candidateGroups;
                            for (var i = 0; i < candidateGroups.length; i++) {
                                var candidateGroup = candidateGroups[i];
                                var id = candidateGroup.id.split("_")[1];
                                var obj = data.result.find(x => x.id == ("1_" + id));
                                if (!$scope.deptPostSelectData[i]) {
                                    $scope.deptPostSelectData[i] = {
                                        dept: obj
                                    }
                                } else {
                                    $scope.deptPostSelectData[i].dept = obj;
                                }
                            }
                        } else {// 默认没有值
                            $scope.dpDeptTableData = data.result;
                        }
                        // 可搜索
                        // angular.element("#dpDept").select2();
                    }
                }, function (error) {
                    console.log("请求失败的回调函数 ", error);
                });
                /*----------------------------------------岗位-------------------------------------------*/
                var url = localStorage.getItem("baseURL") + "/new-flowable/workflow/findAllPosition";
                $http({
                    method: 'GET',
                    url: url,
                    headers: {
                        accessToken: localStorage.getItem("accessToken")
                    }
                }).then(function (response) {
                    var data = response.data;
                    if (data.success) {
                        // 回显选中
                        if ('deptPost' === $scope.allocation && $scope.popup.assignmentObject.idm.candidateGroups.length > 0) {
                            $scope.dpPostTableData = data.result;
                            var candidateGroups = $scope.popup.assignmentObject.idm.candidateGroups;
                            for (var i = 0; i < candidateGroups.length; i++) {
                                var candidateGroup = candidateGroups[i];
                                var id = candidateGroup.id.split("_")[2];
                                var obj = data.result.find(x => x.id == ("2_" + id));
                                if (!$scope.deptPostSelectData[i]) {
                                    $scope.deptPostSelectData[i] = {
                                        post: obj
                                    }
                                } else {
                                    $scope.deptPostSelectData[i].post = obj;
                                }
                            }
                        } else {// 默认没有值
                            $scope.dpPostTableData = data.result;
                        }
                        // 可搜索
                        // angular.element("#dpPost").select2();
                    }
                }, function (error) {
                    console.log("请求失败的回调函数 ", error);
                });
            } else {
                $scope.allocation = '-1'
                console.log("清空！！！！！！");
            }
        };

        initStaticContextForEditing($scope);
        // 初始化自定义数据
        initializesCustomData($scope);

        $scope.$watch('popup.groupFilter', function () {
            $scope.updateGroupFilter();
        });

        $scope.$watch('popup.filter', function () {
            $scope.updateFilter();
        });

        $scope.updateFilter = function () {
            if ($scope.popup.oldFilter == undefined || $scope.popup.oldFilter != $scope.popup.filter) {
                if (!$scope.popup.filter) {
                    $scope.popup.oldFilter = '';
                } else {
                    $scope.popup.oldFilter = $scope.popup.filter;
                }

                if ($scope.popup.filter !== null && $scope.popup.filter !== undefined) {
                    UserService.getFilteredUsers($scope.popup.filter).then(function (result) {
                        var filteredUsers = [];
                        for (var i = 0; i < result.data.length; i++) {
                            var filteredUser = result.data[i];

                            var foundCandidateUser = false;
                            if ($scope.popup.assignmentObject.idm.candidateUsers !== null && $scope.popup.assignmentObject.idm.candidateUsers !== undefined) {
                                for (var j = 0; j < $scope.popup.assignmentObject.idm.candidateUsers.length; j++) {
                                    var candidateUser = $scope.popup.assignmentObject.idm.candidateUsers[j];
                                    if (candidateUser.id === filteredUser.id) {
                                        foundCandidateUser = true;
                                        break;
                                    }
                                }
                            }

                            if (!foundCandidateUser) {
                                filteredUsers.push(filteredUser);
                            }

                        }

                        $scope.popup.userResults = filteredUsers;
                        $scope.resetSelection();
                    });
                }
            }
        };

        $scope.updateGroupFilter = function () {
            if ($scope.popup.oldGroupFilter == undefined || $scope.popup.oldGroupFilter != $scope.popup.groupFilter) {
                if (!$scope.popup.groupFilter) {
                    $scope.popup.oldGroupFilter = '';
                } else {
                    $scope.popup.oldGroupFilter = $scope.popup.groupFilter;
                }

                GroupService.getFilteredGroups($scope.popup.groupFilter).then(function (result) {
                    $scope.popup.groupResults = result.data;
                    $scope.resetGroupSelection();
                });
            }
        };

        $scope.confirmUser = function (user) {
            if (!user) {
                // Selection is done with keyboard, use selection index
                var users = $scope.popup.userResults;
                if ($scope.popup.selectedIndex >= 0 && $scope.popup.selectedIndex < users.length) {
                    user = users[$scope.popup.selectedIndex];
                }
            }

            if (user) {
                if ("user" == $scope.assignmentOption.id) {
                    $scope.popup.assignmentObject.idm.assignee = user;
                } else if ("users" == $scope.assignmentOption.id) {

                    // Only add if not yet part of candidate users
                    var found = false;
                    if ($scope.popup.assignmentObject.idm.candidateUsers) {
                        for (var i = 0; i < $scope.popup.assignmentObject.idm.candidateUsers.length; i++) {
                            if ($scope.popup.assignmentObject.idm.candidateUsers[i].id === user.id) {
                                found = true;
                                break;
                            }
                        }
                    }

                    if (!found) {
                        $scope.addCandidateUser(user);
                    }
                }
            }
        };

        $scope.confirmEmail = function () {
            if ("user" == $scope.assignmentOption.id) {
                $scope.popup.assignmentObject.idm.assignee = {email: $scope.popup.email};
            } else if ("users" == $scope.assignmentOption.id) {

                // Only add if not yet part of candidate users
                var found = false;
                if ($scope.popup.assignmentObject.idm.candidateUsers) {
                    for (var i = 0; i < $scope.popup.assignmentObject.idm.candidateUsers.length; i++) {

                        if ($scope.popup.assignmentObject.idm.candidateUsers[i].id) {
                            if ($scope.popup.assignmentObject.idm.candidateUsers[i].id === user.id) {
                                found = true;
                                break;
                            }
                        } else if ($scope.popup.assignmentObject.idm.candidateUsers[i].email) {
                            if ($scope.popup.assignmentObject.idm.candidateUsers[i].email === $scope.popup.email) {
                                found = true;
                                break;
                            }
                        }
                    }
                }

                if (!found) {
                    $scope.addCandidateUser({email: $scope.popup.email});
                }
            }
        };

        $scope.confirmGroup = function (group) {
            if (!group) {
                // Selection is done with keyboard, use selection index
                var groups = $scope.popup.groupResults;
                if ($scope.popup.selectedGroupIndex >= 0 && $scope.popup.selectedGroupIndex < groups.length) {
                    group = groups[$scope.popup.selectedGroupIndex];
                }
            }

            if (group) {
                // Only add if not yet part of candidate groups
                var found = false;
                if ($scope.popup.assignmentObject.idm.candidateGroups) {
                    for (var i = 0; i < $scope.popup.assignmentObject.idm.candidateGroups.length; i++) {
                        if ($scope.popup.assignmentObject.idm.candidateGroups[i].id === group.id) {
                            found = true;
                            break;
                        }
                    }
                }

                if (!found) {
                    $scope.addCandidateGroup(group);
                }
            }
        };

        $scope.addCandidateUser = function (user) {
            $scope.popup.assignmentObject.idm.candidateUsers.push(user);
        };

        $scope.removeCandidateUser = function (user) {
            var users = $scope.popup.assignmentObject.idm.candidateUsers;
            var indexToRemove = -1;
            for (var i = 0; i < users.length; i++) {
                if (user.id) {
                    if (user.id === users[i].id) {
                        indexToRemove = i;
                        break;
                    }
                } else {
                    if (user.email === users[i].email) {
                        indexToRemove = i;
                        break;
                    }
                }
            }
            if (indexToRemove >= 0) {
                users.splice(indexToRemove, 1);
            }
        };

        $scope.addCandidateGroup = function (group) {
            $scope.popup.assignmentObject.idm.candidateGroups.push(group);
        };

        $scope.removeCandidateGroup = function (group) {
            var groups = $scope.popup.assignmentObject.idm.candidateGroups;
            var indexToRemove = -1;
            for (var i = 0; i < groups.length; i++) {
                if (group.id == groups[i].id) {
                    indexToRemove = i;
                    break;
                }
            }
            if (indexToRemove >= 0) {
                groups.splice(indexToRemove, 1);
            }
        };

        $scope.resetSelection = function () {
            if ($scope.popup.userResults && $scope.popup.userResults.length > 0) {
                $scope.popup.selectedIndex = 0;
            } else {
                $scope.popup.selectedIndex = -1;
            }
        };

        $scope.nextUser = function () {
            var users = $scope.popup.userResults;
            if (users && users.length > 0 && $scope.popup.selectedIndex < users.length - 1) {
                $scope.popup.selectedIndex += 1;
            }
        };

        $scope.previousUser = function () {
            var users = $scope.popup.userResults;
            if (users && users.length > 0 && $scope.popup.selectedIndex > 0) {
                $scope.popup.selectedIndex -= 1;
            }
        };

        $scope.resetGroupSelection = function () {
            if ($scope.popup.groupResults && $scope.popup.groupResults.length > 0) {
                $scope.popup.selectedGroupIndex = 0;
            } else {
                $scope.popup.selectedGroupIndex = -1;
            }
        };

        $scope.nextGroup = function () {
            var groups = $scope.popup.groupResults;
            if (groups && groups.length > 0 && $scope.popup.selectedGroupIndex < groups.length - 1) {
                $scope.popup.selectedGroupIndex += 1;
            }
        };

        $scope.previousGroup = function () {
            var groups = $scope.popup.groupResults;
            if (groups && groups.length > 0 && $scope.popup.selectedGroupIndex > 0) {
                $scope.popup.selectedGroupIndex -= 1;
            }
        };

        $scope.removeAssignee = function () {
            $scope.popup.assignmentObject.idm.assignee = undefined;
        };

        // Click handler for + button after enum value
        $scope.addCandidateUserValue = function (index) {
            $scope.popup.assignmentObject.static.candidateUsers.splice(index + 1, 0, {value: ''});
        };

        // Click handler for - button after enum value
        $scope.removeCandidateUserValue = function (index) {
            $scope.popup.assignmentObject.static.candidateUsers.splice(index, 1);
        };

        // Click handler for + button after enum value
        $scope.addCandidateGroupValue = function (index) {
            $scope.popup.assignmentObject.static.candidateGroups.splice(index + 1, 0, {value: ''});
        };

        // Click handler for - button after enum value
        $scope.removeCandidateGroupValue = function (index) {
            $scope.popup.assignmentObject.static.candidateGroups.splice(index, 1);
        };

        $scope.setSearchType = function () {
            $scope.popup.assignmentObject.assignmentSourceType = 'search';
        };

        $scope.allSteps = EDITOR.UTIL.collectSortedElementsFromPrecedingElements($scope.selectedShape);

        $scope.save = function () {
            handleAssignmentInput($scope.popup.assignmentObject.static);

            $scope.assignment.type = $scope.popup.assignmentObject.type;//idm身份存储、static固定值

            if ('idm' === $scope.popup.assignmentObject.type) { // IDM
                // 如果不是自定义，需要清空allocation
                if ($scope.assignmentOption.id !== "custom") {
                    $scope.allocation = "-1";
                }

                //Construct an IDM object to be saved to the process model.
                var idm = {
                    type: $scope.assignmentOption.id,
                    showType: $scope.assignmentOption.id, // 新增一个类型用于存放类型，用于回显页面展示
                    customType: $scope.allocation, // 新增一个类型用于存放自定义类型，用于回显页面展示：$scope.allocationOperations
                };

                if ('user' == idm.type) {
                    if ($scope.popup.assignmentObject.idm.assignee) {
                        idm.assignee = $scope.popup.assignmentObject.idm.assignee;
                    }
                } else if ('users' == idm.type) {
                    if ($scope.popup.assignmentObject.idm.candidateUsers && $scope.popup.assignmentObject.idm.candidateUsers.length > 0) {
                        idm.candidateUsers = $scope.popup.assignmentObject.idm.candidateUsers;
                    }
                } else if ('groups' == idm.type) {
                    if ($scope.popup.assignmentObject.idm.candidateGroups && $scope.popup.assignmentObject.idm.candidateGroups.length > 0) {
                        idm.candidateGroups = $scope.popup.assignmentObject.idm.candidateGroups;
                    }
                } else if ('custom' == idm.type) {
                    // 自定义用户权限
                    console.log("自定义用户权限选中类型：", $scope.allocation);
                    // 用户数据
                    if ('user' === $scope.allocation && $scope.userSelectData && $scope.userSelectData.length > 0) {
                        idm.candidateUsers.length = 0//清空数据
                        idm.candidateUsers = $scope.userSelectData;
                        idm.type = 'users';
                    }
                    // 部门数据
                    if ('dept' === $scope.allocation && $scope.deptSelectData && $scope.deptSelectData.length > 0) {
                        idm.candidateGroups = $scope.deptSelectData;
                        idm.type = 'groups';
                    }
                    // 岗位数据
                    if ('post' === $scope.allocation && $scope.postSelectData && $scope.postSelectData.length > 0) {
                        idm.candidateGroups = $scope.postSelectData;
                        idm.type = 'groups';
                    }
                    // 岗位组数据
                    if ('group' === $scope.allocation && $scope.groupSelectData && $scope.groupSelectData.length > 0) {
                        idm.candidateGroups = $scope.groupSelectData;
                        idm.type = 'groups';
                    }
                    // 岗位等级数据
                    if ('level' === $scope.allocation && $scope.levelSelectData && $scope.levelSelectData.length > 0) {
                        idm.candidateGroups = $scope.levelSelectData;
                        idm.type = 'groups';
                    }
                    // 部门岗位数据
                    if ('deptPost' === $scope.allocation) {
                        var length = $scope.deptPostSelectData.length;
                        if ($scope.deptPostSelectData && $scope.deptPostSelectData.length > 0) {
                            const isEmpty = $scope.deptPostSelectData.find(item => {
                                var dept = item.dept;
                                var post = item.post;
                                var deptIsEmpty = Object.keys(dept).length === 0;
                                var postIsEmpty = Object.keys(post).length === 0;
                                return deptIsEmpty || postIsEmpty;
                            })
                            if (isEmpty) {
                                alert("请将数据填写完整！")
                                return
                            } else {
                                var deptPosts = [];
                                for (let i = 0; i < $scope.deptPostSelectData.length; i++) {
                                    var item = $scope.deptPostSelectData[i];
                                    var dept = item.dept.id;
                                    var post = item.post.id;
                                    var deptId = dept.split("_")[1];
                                    var postId = post.split("_")[1];
                                    // 5，这个前缀应该与CustomUserTypeEnum中DEPT_POST的属性对应
                                    var deptPost = 5 + "_" + deptId + "_" + postId;
                                    deptPosts.push({id: deptPost});
                                }
                                console.log("选中数据:", deptPosts);
                                idm.candidateGroups = deptPosts;
                                idm.type = 'groups';
                            }
                        }
                    }
                }
                console.log("选中IDM信息：", idm);
                $scope.popup.assignmentObject.static = undefined;
                $scope.assignment.idm = idm;
                $scope.assignment.assignee = undefined;
                $scope.assignment.candidateUsers = undefined;
                $scope.assignment.candidateGroups = undefined;
            }

            if ('static' === $scope.popup.assignmentObject.type) { // IDM
                $scope.popup.assignmentObject.idm = undefined;
                $scope.assignment.idm = undefined;
                $scope.assignment.assignee = $scope.popup.assignmentObject.static.assignee;
                $scope.assignment.candidateUsers = $scope.popup.assignmentObject.static.candidateUsers;
                $scope.assignment.candidateGroups = $scope.popup.assignmentObject.static.candidateGroups;
            }

            $scope.property.value = {};
            $scope.property.value.assignment = $scope.assignment;
            $scope.updatePropertyInModel($scope.property);
            $scope.close();
        };

        // Close button handler
        $scope.close = function () {
            $scope.property.mode = 'read';
            $scope.$hide();
        };

        var handleAssignmentInput = function ($assignment) {

            function isEmptyString(value) {
                return (value === undefined || value === null || value.trim().length === 0);
            }

            if (isEmptyString($assignment.assignee)) {
                $assignment.assignee = undefined;
            }
            var toRemoveIndexes;
            var removedItems = 0;
            var i = 0;
            if ($assignment.candidateUsers) {
                toRemoveIndexes = [];
                for (i = 0; i < $assignment.candidateUsers.length; i++) {
                    if (isEmptyString($assignment.candidateUsers[i].value)) {
                        toRemoveIndexes[toRemoveIndexes.length] = i;
                    }
                }

                if (toRemoveIndexes.length == $assignment.candidateUsers.length) {
                    $assignment.candidateUsers = undefined;
                } else {
                    removedItems = 0;
                    for (i = 0; i < toRemoveIndexes.length; i++) {
                        $assignment.candidateUsers.splice(toRemoveIndexes[i] - removedItems, 1);
                        removedItems++;
                    }
                }
            }

            if ($assignment.candidateGroups) {
                toRemoveIndexes = [];
                for (i = 0; i < $assignment.candidateGroups.length; i++) {
                    if (isEmptyString($assignment.candidateGroups[i].value)) {
                        toRemoveIndexes[toRemoveIndexes.length] = i;
                    }
                }

                if (toRemoveIndexes.length == $assignment.candidateGroups.length) {
                    $assignment.candidateGroups = undefined;
                } else {
                    removedItems = 0;
                    for (i = 0; i < toRemoveIndexes.length; i++) {
                        $assignment.candidateGroups.splice(toRemoveIndexes[i] - removedItems, 1);
                        removedItems++;
                    }
                }
            }
        };

        function initStaticContextForEditing($scope) {
            if (!$scope.popup.assignmentObject.static.candidateUsers || $scope.popup.assignmentObject.static.candidateUsers.length == 0) {
                $scope.popup.assignmentObject.static.candidateUsers = [{value: ''}];
            }
            if (!$scope.popup.assignmentObject.static.candidateGroups || $scope.popup.assignmentObject.static.candidateGroups.length == 0) {
                $scope.popup.assignmentObject.static.candidateGroups = [{value: ''}];
            }
        }

        // 初始化自定义数据
        function initializesCustomData($scope) {
            console.log("初始化用户信息数据(properties-assignment-controller.js)......");
            // 默认值
            $scope.allocationSelect = {};
            $scope.tableLoading = false;// 表格数据是否加载完成
            // 用户数据
            $scope.userTableData = [];
            $scope.userSelectData = [];
            // 部门数据
            $scope.deptTableData = [];
            $scope.deptSelectData = [];
            // 岗位数据
            $scope.postTableData = [];
            $scope.postSelectData = [];
            // 岗位组数据
            $scope.groupTableData = [];
            $scope.groupSelectData = [];
            // 岗位等级数据
            $scope.levelTableData = [];
            $scope.levelSelectData = [];
            // 部门岗位数据
            $scope.dpDeptTableData = [];
            $scope.dpPostTableData = [];
            $scope.deptPostSelectData = [{dept: "", post: ""}];
            // 回显信息
            if ($scope.assignment.idm && $scope.assignment.idm.showType === "custom") {
                $scope.allocation = $scope.assignment.idm.customType;
                $scope.allocationSelect = $scope.allocationOperations.find(it => it.type === $scope.assignment.idm.customType)
                $scope.allocationChange("0");//加载数据
            }
        }

        $scope.userClick = function (e) {
            if (e.isChecked) {//选中
                $scope.userSelectData.push(e);
            } else {//取消
                $scope.userSelectData = $scope.userSelectData.filter(item => item.id !== e.id);
            }
            console.log("选中的用户：", $scope.userSelectData);
        };
        $scope.deptClick = function (e) {
            if (e.isChecked) {//选中
                $scope.deptSelectData.push(e);
            } else {//取消
                $scope.deptSelectData = $scope.deptSelectData.filter(item => item.id !== e.id);
            }
            console.log("选中的部门：", $scope.deptSelectData);
        };
        $scope.postClick = function (e) {
            if (e.isChecked) {//选中
                $scope.postSelectData.push(e);
            } else {//取消
                $scope.postSelectData = $scope.postSelectData.filter(item => item.id !== e.id);
            }
            console.log("选中的岗位：", $scope.postSelectData);
        };
        $scope.groupClick = function (e) {
            if (e.isChecked) {//选中
                $scope.groupSelectData.push(e);
            } else {//取消
                $scope.groupSelectData = $scope.groupSelectData.filter(item => item.id !== e.id);
            }
            console.log("选中的组：", $scope.groupSelectData);
        };
        $scope.levelClick = function (e) {
            if (e.isChecked) {//选中
                $scope.levelSelectData.push(e);
            } else {//取消
                $scope.levelSelectData = $scope.levelSelectData.filter(item => item.id !== e.id);
            }
            console.log("选中的等级：", $scope.levelSelectData);
        };
        // 部门岗位
        $scope.addDeptPost = function (e) {
            var obj = {dept: "", post: ""};
            $scope.deptPostSelectData.push(obj)
            console.log("添加的部门岗位(部门)：", e);
        };
        $scope.delDeptPost = function (e) {
            delArrayByKey($scope.deptPostSelectData, e.$$hashKey);
            console.log("删除的部门岗位(岗位)：", e);
        };
        $scope.dpDeptClick = function () {
            console.log("选中的部门岗位(部门)：", $scope.deptPostSelectData);
        };
        $scope.dpPostClick = function () {
            console.log("选中的部门岗位(岗位)：", $scope.deptPostSelectData);
        };

        /***
         *  通过hashKey删除数组元素
         * @param arr
         * @param hashKey
         */
        function delArrayByKey(arr, hashKey) {
            console.log("数组：", arr);
            for (var i = 0; i < arr.length; i++) {
                if (arr[i].$$hashKey === hashKey) { // 查找元素并删除
                    arr.splice(i, 1);
                    break; // 找到并删除后退出循环
                }
            }
        }
    }]);
